package com.ndp.fb.mq.service.schedulerservice.audience;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.enums.publish.OptimizationGoal;
import com.ndp.fb.fbagent.service.TargetingSpecFBService;
import com.ndp.fb.model.fbagent.param.APIPriority;
import com.ndp.fb.model.fbagent.param.ApiCallBackTarget;
import com.ndp.fb.model.fbagent.param.useraudience.TargetingSpecParam;
import com.ndp.fb.mq.api.service.schedulerservice.audience.AudienceSchedulerService;
import com.ndp.fb.rdb.api.AudienceManagerRdbService;
import com.ndp.fb.rdb.api.FbUserRdbService;
import com.ndp.fb.model.rdb.AudienceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sisi.chen on 2016/4/28.
 */
@Service
public class AudienceSchedulerServiceImpl implements AudienceSchedulerService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Reference
    private AudienceManagerRdbService audienceManagerRdbService;

    @Reference
    private FbUserRdbService fbUserRdbService;

    @Reference
    private TargetingSpecFBService targetingSpecFBService;

    @Override
    public void refreshUser() {
        logger.info("开始刷新受众用户数");
        List<AudienceManager> audiences = audienceManagerRdbService.findAll();
        if (CollectionUtils.isEmpty(audiences)){
            return;
        }

        for (AudienceManager audience : audiences){
            String accessToken = fbUserRdbService.getTokenByUserId(audience.getUserId());
            TargetingSpecParam targetingSpecReachEstimateParam = new TargetingSpecParam();
            targetingSpecReachEstimateParam.setTargetingSpec(audience.getFbTargeting());
            targetingSpecReachEstimateParam.setCallBack(true);
            targetingSpecReachEstimateParam.setFbAccountId(audience.getFbAccountId());
            targetingSpecReachEstimateParam.setAccessToken(accessToken);
            targetingSpecReachEstimateParam.setApiCallbackTargetType(ApiCallBackTarget.AdPublish.RefreshAudienceUser.getTargetType());
            targetingSpecReachEstimateParam.setApiPriorityCode(APIPriority.UserAudienceReach.getCode());
            targetingSpecReachEstimateParam.setOptimizeFor(OptimizationGoal.NONE.getCode());
            Map<String, String> equipment = new HashMap<>();
            equipment.put("id",audience.getId() + "");
            targetingSpecReachEstimateParam.setEquipment(equipment);
            targetingSpecFBService.targetingSpecReachEstimate(targetingSpecReachEstimateParam);
        }
        logger.info("刷新受众用户数结束");
    }
}
